import React, { useEffect, useState } from 'react';
import { Drawer, Spin, message, Timeline, Radio, Tooltip } from 'antd';
import {
  DownSquareOutlined,
  UpSquareOutlined,
  // @ts-ignore
} from '#/utils/antdIcons';
// @ts-ignore
import InfiniteScroll from 'react-infinite-scroller';
import { AntdBaseTable } from '@/base/TBaseTable';
import moment from 'moment';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import { postFindOperationLog } from '../../../service';
import type {
  IPostFindOperationLogParamsType,
  IFindOperationLogDataType,
  IFindOperationLogDataListType,
} from '../../../type';
import { IUseType } from '../../../type';
import { smoothStatusOptions } from '../../../dictionary';
import styles from './index.less';

interface IProps {
  /**
   * params
   */
  queryValue?: IPostFindOperationLogParamsType;
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
}

const OperationLog = (props: IProps) => {
  const { visible = false, queryValue, onClose } = props;
  const [data, setData] = useState<IFindOperationLogDataType[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [currentData, setCurrentData] = useState<IFindOperationLogDataType[]>([]);

  // 初始化数据
  const fetchData = async (val: IPostFindOperationLogParamsType) => {
    setLoading(true);
    setError(false);
    const res = await postFindOperationLog(val);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = (res?.data || []).map((item: IFindOperationLogDataType, index: number) => ({
        ...item,
        id: index + 1,
      }));
      setData(_data);
      setCurrentData(_data.length > 20 ? _data?.splice(0, 20) : _data);
      setError(false);
    } else {
      setError(true);
      message.info(res?.message || '系统异常');
    }
    setLoading(false);
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  const loadMore = (currentPage: number) => {
    if (!hasMore) return;
    setIsLoading(true);
    setHasMore(data.length > 20 * currentPage ? true : false);
    const _data = [...data].splice(currentPage * 20, 20);
    setTimeout(() => {
      setIsLoading(false);
    }, 1000);
    setCurrentData([...currentData, ..._data]);
  };

  const onSpread = (record: IFindOperationLogDataType) => {
    let _data = [...data];
    let _currentData = [...currentData];
    _data = _data.map((item) => {
      return {
        ...item,
        isSpread: item.id === record.id ? !item.isSpread : item?.isSpread,
      };
    });
    _currentData = _currentData.map((item) => {
      return {
        ...item,
        isSpread: item.id === record.id ? !item.isSpread : item?.isSpread,
      };
    });
    setData(_data);
    setCurrentData(_currentData);
  };

  useEffect(() => {
    if (queryValue?.markDate && queryValue?.stationId && queryValue?.type && visible) {
      fetchData(queryValue);
    }
  }, [visible]);

  const columns = [
    {
      code: 'time',
      name: '时间段',
      align: 'center',
      width: 120,
      render(v: string) {
        return <div className={styles.timeSlot}>{v}</div>;
      },
    },
    {
      code: 'dataSourceName',
      name: (
        <div className={styles.dataSourceId}>
          <div className={styles.radio}>{''}</div>
          <div className={styles.ratio}>调整比例(%)</div>
          <div className={styles.predictSource}>基准预测源</div>
          <div className={styles.maxNum}>最大值</div>
          <div className={styles.minNum}>最小值</div>
        </div>
      ),
      width: 295,
      render(v: string, record: IFindOperationLogDataListType) {
        return (
          <div className={styles.dataSourceIdShow}>
            <div className={styles.radio}>
              <Radio checked={record?.useType === IUseType.DATASOURCE} disabled />
            </div>
            <div className={styles.ratio}>{record?.rateValue ?? 100}</div>
            <div className={styles.predictSource}>
              <Tooltip placement="topLeft" title={v}>
                {v}
              </Tooltip>
            </div>
            <div className={styles.maxNum}>{record?.max ?? '0.000'}</div>
            <div className={styles.minNum}>{record?.min ?? '0.000'}</div>
          </div>
        );
      },
    },
    {
      code: 'fixedValue',
      name: (
        <div className={styles.fixedValue}>
          <div className={styles.radio}>{''}</div>
          <div className={styles.name}>固定值</div>
        </div>
      ),
      width: 100,
      render(v: string, record: IFindOperationLogDataListType) {
        return (
          <div className={styles.fixedValueShow}>
            <div className={styles.radio}>
              <Radio checked={record?.useType === IUseType.FIXATION} disabled />
            </div>
            <div className={styles.fixedValueShowInput}>{record?.fixation ?? '0.000'}</div>
          </div>
        );
      },
    },
  ];

  return (
    <Drawer
      width={680}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>操作日志</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin spinning={loading} />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : data.length ? (
          <Spin spinning={isLoading} className={styles.spinloading}>
            <div className={styles.content}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={loadMore}
                hasMore={!loading && hasMore}
                useWindow={false}
                className={styles.infiniteScroll}
              >
                <Timeline>
                  {currentData.map((item, index: number) => {
                    const _smoothStatusLabel =
                      smoothStatusOptions.find((i) => i.value === item.smoothStatus)?.label ||
                      '未平滑';
                    return (
                      <Timeline.Item key={index}>
                        <div className={styles.timelineItem}>
                          <div className={styles.header}>
                            <div className={styles.title}>
                              <div className={styles.date}>
                                {moment(item.operationTime).format('YYYY.MM.DD HH:mm:ss')}
                              </div>
                              <div className={styles.type}>策略更新</div>
                              <div className={styles.spread} onClick={() => onSpread(item)}>
                                {item?.isSpread ? (
                                  <UpSquareOutlined className={styles.spreadLogo} />
                                ) : (
                                  <DownSquareOutlined className={styles.spreadLogo} />
                                )}
                              </div>
                            </div>
                            <div className={styles.updateUser}>
                              <span>操作人：</span>
                              <span className={styles.operationUser}>{item.operationUser}</span>
                            </div>
                          </div>
                          {item.isSpread && (
                            <div className={styles.bottom}>
                              <div className={styles.smoothStatus}>
                                平滑算法：{_smoothStatusLabel}
                              </div>
                              <div className={styles.antdBaseTable}>
                                <AntdBaseTable
                                  dataSource={item.dataList || []}
                                  columns={columns as any}
                                  style={{
                                    '--row-height': '28px',
                                    // '--header-bgcolor': '#383C3E',
                                    '--header-row-height': '28px',
                                    '--cell-padding': '4px 16px',
                                    '--cell-border-vertical': '1px solid #4E5154',
                                    '--header-cell-border-vertical': '1px solid #4E5154',
                                    '--hover-bgcolor': '#222629',
                                    '--bgcolor': '#222629',
                                  }}
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
                {/* {!hasMore && data.length !== 0 && (
                  <div className={styles.loader} key={0}>
                    已经到底了～
                  </div>
                )} */}
              </InfiniteScroll>
            </div>
          </Spin>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default OperationLog;
